<template>
    <div id="new-class">
        <el-breadcrumb separator="/" class="common-bread">
            <el-breadcrumb-item :to="{ path: '/class' }">班级管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{operationText}}班级</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="form mt10 contentBox">
            <div class="list_head">
                <span class="head_name">班级信息</span>
                <el-button type="primary" @click="$router.push('/class')" class="fr ml10">取消</el-button>
                <el-button type="primary" @click="save" class="fr">保存</el-button>
            </div>
            <el-form label-width="120px" :model="form" :rules="rules" ref="form">
                <el-form-item label="学校：" prop="schoolName">
                    <el-autocomplete v-model="form.schoolName" :fetch-suggestions="querySearch" placeholder="请输入使用学校" @select="handleSelect"
                        clearable></el-autocomplete>
                </el-form-item>

                <el-form-item label="年级：" prop="gradeId" ref="grade">
                    <el-select v-model="form.gradeId" @change="getSavednumber()">
                        <el-option :label='item.gradeName' :value='item.gradeId' :key='item.gradeId' v-for="item in grades"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班级：" prop="number" ref="class">
                    <el-select v-model="form.number">
                        <el-option :label='item.label' :value='item.value' :key='index' v-for="(item,index) in classes"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班级名称：" prop="className">
                    <el-input v-model="form.className"></el-input>
                </el-form-item>
                <el-form-item label="班级编号：" prop="classNumber">
                    <el-input v-model="form.classNumber"></el-input>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";
    export default {
        data() {
            let validBlank = (rule, value, callback) => {
                value = value.trim();
                if (value) {
                    if (value.length > 50) {
                        callback(new Error("字符长度不能超过50个字符"));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error("不能为空或空格"));
                }
            };

            return {
                id: "",
                operationText: "添加",
                schoolId: "",
                schools: [],
                schoolType: [],
                grades: [],
                classes: [],
                form: {
                    schoolName: "",
                    className: "",
                    gradeId: "",
                    number: "",
                    classNumber: ""
                },
                rules: {
                    schoolName: [{
                        required: true, message: "学校名称不能为空", trigger: "change"
                    }],
                    number: [
                        { required: true, message: "请选择班级", trigger: "change" }
                    ],
                    classNumber: [
                        { required: true, message: "班级编号不能为空", trigger: "blur" },
                        { validator: validBlank }
                    ],
                    gradeId: [
                        { required: true, message: "请选择年级", trigger: "change" }
                    ]
                }
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.getSchools();
            this.$util.setStore("classSelect", 1);
            this.id = this.$util.getUrlParam("id");
            if (this.id) {
                this.operationText = "编辑";
                this.getDetail();
            }
        },
        methods: {
            //获取学校列表
            getSchools() {
                this.$util.getSchools().then(schools => {
                    schools.forEach(item => {
                        this.schools.push({
                            value: item.name,
                            schoolId: item.schoolId,
                            haveHigh: item.haveHigh,
                            haveMiddle: item.haveMiddle,
                            havePrimary: item.havePrimary
                        })
                    });
                });
            },
            //根据年级和学校获取已经存在班级序号
            getSavednumber(num) {
                this.$axios.get("/adminapi/v1/tools/classes/classNum/list", {
                    params: {
                        grade: this.form.gradeId,
                        schoolId: this.schoolId
                    }
                }).then(response => {
                    if (response.data.error == 10000) {
                        let list = response.data.data || [];
                        let newArray = [];
                        for (let i = 0; i < 40; i++) {
                            if (num && num == i + 1) newArray.push({ label: i + 1 + "班", value: i + 1 });
                            if (!list.includes(i + 1 + "")) newArray.push({ label: i + 1 + "班", value: i + 1 });
                        }
                        this.$refs.class.resetField();
                        this.classes = newArray;
                        if (num) this.form.number = num * 1;
                    }
                })
            },
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            handleSelect(item) {
                this.schoolId = item.schoolId;
                let schoolType = [];
                if (item.haveHigh) schoolType.push("高中");
                if (item.haveMiddle) schoolType.push("初中");
                if (item.havePrimary) schoolType.push("小学");
                this.getSavednumber();
                this.$refs.grade.resetField();
                this.$refs.class.resetField();
                this.grades = this.$util.getGrades(schoolType);
            },
            save() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        let requestParam = {
                            schoolId: this.schoolId,
                            name: this.form.className.trim(),
                            grade: this.form.gradeId,
                            classNumber: this.form.classNumber.trim(),//班级编号
                            number: this.form.number//班级序号
                        }

                        if (this.id) requestParam.classId = this.id;
                        this.$axios.post("/adminapi/v1/tools/classes/addOrEdit", requestParam).then(response => {
                            if (response.data.error == 10000) {
                                this.$router.push("/class");
                                this.$util.successMsg("保存成功");
                            } else {
                                this.$util.errorMsg(response.data.message);
                            }
                        })
                    }
                })
            },
            //获取学校详情
            getDetail() {
                this.$axios.get("/adminapi/v1/tools/classes/info?classId=" + this.id).then(response => {
                    if (response.data.error == 10000) {
                        let info = response.data.data;

                        this.schoolId = info.schoolId;
                        this.form = {
                            schoolName: info.schoolName,
                            gradeId: info.grade * 1,
                            number: 0,
                            className: info.name,
                            classNumber: info.classNumber,
                        };
                        this.grades = this.$util.getGrades();
                        this.getSavednumber(info.number);
                    }
                })
            },
        }
    }
</script>
<style>
    #new-class {
        height: inherit;
    }

    #new-class .el-select {
        width: 300px;
    }

    #new-class .el-date-editor.el-input,
    #new-class .el-date-editor.el-input__inner {
        width: 300px;
    }

    #new-class .el-select>.el-input,
    #new-class .select-head>.el-input {
        width: 300px;
    }
</style>